<template>
  <div class="vehicle-info-page">

    <!-- 顶部信息栏-->
    <div class="top-info-bar">
      <div class="top-row">
        <div class="dropdown-container" @click="showVehiclePopup = true">
          <div class="dropdown-title">
            <span class="title-text">{{ currentVehicle?.vehicleName || '我的车辆' }}</span>
            <van-icon name="arrow-down" />
          </div>
        </div>
        <div class="top-right">
          <div class="refresh-button" :class="{ spinning: isRefreshing }" @click="onRefreshClick" title="刷新">
            <van-icon name="replay" size="18" />
          </div>
        </div>
      </div>


      <div class="status-chips">
        <div class="chip signal" :class="signalClass">
          <div class="bars">
            <span v-for="n in 5" :key="n" class="bar" :class="{ active: n <= signalBars }"></span>
          </div>
          <span class="chip-text">{{ signalDbm != null ? `${signalDbm} dBm` : '无信号' }}</span>
        </div>
        <div class="chip lock" :class="isLocked ? 'ok' : 'warn'">
          <span class="chip-icon svg">
            <!-- 锁定图标 -->
            <svg v-if="isLocked" :key="'locked-chip'" xmlns="http://www.w3.org/2000/svg" width="16" height="16"
              viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
              stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
            </svg>
            <!-- 解锁图标（开口的锁） -->
            <svg v-else :key="'unlocked-chip'" class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"
              width="16" height="16" fill="currentColor">
              <path
                d="M892.342857 402.285714H504.685714v-146.285714c0-131.657143-102.4-234.057143-234.057143-234.057143C138.971429 21.942857 36.571429 124.342857 36.571429 256v153.6H124.342857V256c0-80.457143 65.828571-146.285714 146.285714-146.285714s146.285714 65.828571 146.285715 146.285714v146.285714H285.257143c-36.571429 0-65.828571 29.257143-65.828572 58.514286v431.542857c0 29.257143 29.257143 58.514286 58.514286 58.514286h614.4c29.257143 0 58.514286-29.257143 58.514286-58.514286V460.8c0-29.257143-21.942857-58.514286-58.514286-58.514286z m-270.628571 292.571429v95.085714c0 7.314286 0 7.314286-7.314286 7.314286h-51.2c-7.314286 0-7.314286 0-7.314286-7.314286v-95.085714c-21.942857-14.628571-43.885714-36.571429-43.885714-65.828572 0-43.885714 29.257143-73.142857 73.142857-73.142857s73.142857 36.571429 73.142857 73.142857c7.314286 29.257143-14.628571 51.2-36.571428 65.828572z" />
            </svg>
          </span>
          <span class="chip-text">{{ isLocked ? '已关锁' : '未关锁' }}</span>
        </div>

        <div class="chip online" :class="currentVehicle?.onlineStatus === 'online' ? 'ok' : 'warn'">
          <span class="dot" :class="currentVehicle?.onlineStatus === 'online' ? 'on' : 'off'"></span>
          <span class="chip-text">{{ currentVehicle?.onlineStatus === 'online' ? '在线' : '离线' }}</span>
        </div>
      </div>
    </div>


    <!-- 车辆切换弹出层 -->

    <van-popup v-model:show="showVehiclePopup" position="bottom" round :style="{ maxHeight: '60%' }"
      :safe-area-inset-bottom="true" class="vehicle-popup">
      <div class="vehicle-popup-header">
        <div class="popup-title">选择车辆</div>
        <div class="close-icon" @click="showVehiclePopup = false">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </div>
      </div>
      <div class="popup-scroll-container">
        <div class="vehicle-list">
          <div v-for="(vehicle, index) in vehicleList" :key="vehicle.vinNo" class="vehicle-item"
            :class="{ active: currentIndex === index }" @click="switchVehicle(index)">
            <div class="vehicle-item-image">
              <img :src="vehicle.customImage || vehicle.vehicleScalePicUrl" :alt="vehicle.vehicleName" />
            </div>
            <div class="vehicle-item-info">
              <div class="vehicle-item-name">{{ vehicle.vehicleName }}</div>
              <div class="vehicle-item-type">{{ vehicle.vehicleType }} · {{ vehicle.vehicleTypeName }}</div>
              <div v-if="vehicle.totalRideMile" class="vehicle-item-mileage">总里程: {{ vehicle.totalRideMile }}km</div>
            </div>
            <div class="vehicle-item-status">
              <div class="battery-info">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="1" y="6" width="18" height="12" rx="2" ry="2"></rect>
                  <line x1="23" y1="13" x2="23" y2="11"></line>
                </svg>
                {{ vehicle.bmssoc || getVehicleIotProperty(vehicle, 'BMSSOC') || '0' }}%
              </div>
              <div class="online-status" :class="vehicle.onlineStatus === 'online' ? 'online' : 'offline'">
                {{ vehicle.onlineStatus === 'online' ? '在线' : '离线' }}
              </div>
            </div>
            <div class="vehicle-select-indicator" v-if="currentIndex === index">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="20 6 9 17 4 12"></polyline>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 车辆图片 -->
    <div class="vehicle-image-container" @click="goToVehicleDetail">
      <div class="vehicle-image-wrapper">
        <img :src="currentVehicleImage" :alt="currentVehicle?.vehicleName" class="vehicle-image" />
      </div>
    </div>

    <!-- 位置信息 -->
    <div class="location-info" @click="goToLocation">
      <div class="location-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#4285F4"
          stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
          <circle cx="12" cy="10" r="3"></circle>
        </svg>
      </div>
      <div class="location-text">{{ address }}</div>
    </div>

    <!-- 车辆数据 -->
    <div class="vehicle-data-container">
      <!-- 左侧：续航里程与电量 -->
      <div class="data-box left-data" @click="goToBatteryDetail">
        <div class="data-content">
          <div class="data-section">
            <div class="data-title">预估里程</div>
            <div class="data-value-large">
              {{ currentVehicle?.hmiRidableMile || getIotPropertyValue('HMIRidableMile') || '0' }}<span
                class="data-unit">km</span>
            </div>
          </div>

          <div class="data-section">
            <div class="data-title">{{ isCharging ? '充电中' : '剩余电量' }}</div>
            <div class="data-value-large">
              {{ actualSoc }}<span class="data-unit">%</span>
            </div>
            <div class="battery-bar">
              <div class="battery-level" :class="{ charging: isCharging }"
                :style="{ width: `${isCharging ? displayedSoc : actualSoc}%` }"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：功能按钮 -->
      <div class="data-box right-data">
        <div class="function-grid">
          <div v-if="isLocked" :class="['function-item', 'no-select', { pressing: isLongPressing }]"
            @touchstart.prevent.stop="startLongPress" @touchend.prevent.stop="endLongPress"
            @touchcancel.prevent.stop="endLongPress" @mousedown.prevent.stop="startLongPress"
            @mouseup.prevent.stop="endLongPress" @mouseleave.prevent.stop="endLongPress" @contextmenu.prevent
            :style="{ '--pressDeg': (pressProgress * 3.6) + 'deg' }">
            <div v-if="isLongPressing" class="press-ring" aria-hidden="true"></div>
            <div class="function-icon lock-icon">
              <!-- 闭锁图标（当前为关锁状态） -->
              <svg :key="'locked-action-btn'" xmlns="http://www.w3.org/2000/svg" width="22" height="22"
                viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                stroke-linejoin="round">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
              </svg>
            </div>
            <div class="function-label">
              <template v-if="isLongPressing">
                <span class="pressing-text">按住中...</span>
                <div class="progress-bar">
                  <div class="progress" :style="{ width: `${pressProgress}%` }"></div>
                </div>
              </template>
              <template v-else>长按开锁</template>
            </div>
          </div>
          <div v-else :class="['function-item', 'no-select', 'unlock-state', { pressing: isLongPressing }]"
            @touchstart.prevent.stop="startLongPress" @touchend.prevent.stop="endLongPress"
            @touchcancel.prevent.stop="endLongPress" @mousedown.prevent.stop="startLongPress"
            @mouseup.prevent.stop="endLongPress" @mouseleave.prevent.stop="endLongPress" @contextmenu.prevent
            :style="{ '--pressDeg': (pressProgress * 3.6) + 'deg' }">
            <div v-if="isLongPressing" class="press-ring" aria-hidden="true"></div>
            <div class="function-icon unlock-icon">
              <!-- 开锁图标（当前为未关锁状态） -->
              <svg :key="'unlocked-action-btn'" class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"
                width="24" height="24" fill="currentColor">
                <path
                  d="M892.342857 402.285714H504.685714v-146.285714c0-131.657143-102.4-234.057143-234.057143-234.057143C138.971429 21.942857 36.571429 124.342857 36.571429 256v153.6H124.342857V256c0-80.457143 65.828571-146.285714 146.285714-146.285714s146.285714 65.828571 146.285715 146.285714v146.285714H285.257143c-36.571429 0-65.828571 29.257143-65.828572 58.514286v431.542857c0 29.257143 29.257143 58.514286 58.514286 58.514286h614.4c29.257143 0 58.514286-29.257143 58.514286-58.514286V460.8c0-29.257143-21.942857-58.514286-58.514286-58.514286z m-270.628571 292.571429v95.085714c0 7.314286 0 7.314286-7.314286 7.314286h-51.2c-7.314286 0-7.314286 0-7.314286-7.314286v-95.085714c-21.942857-14.628571-43.885714-36.571429-43.885714-65.828572 0-43.885714 29.257143-73.142857 73.142857-73.142857s73.142857 36.571429 73.142857 73.142857c7.314286 29.257143-14.628571 51.2-36.571428 65.828572z" />
              </svg>
            </div>
            <div class="function-label">
              <template v-if="isLongPressing">
                <span class="pressing-text">按住中...</span>
                <div class="progress-bar">
                  <div class="progress" :style="{ width: `${pressProgress}%` }"></div>
                </div>
              </template>
              <template v-else>长按关锁</template>
            </div>
          </div>
          <div class="function-item" @click="openMotoPlay">
            <div class="function-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="4" y="4" width="16" height="16" rx="2" ry="2"></rect>
                <rect x="9" y="9" width="6" height="6"></rect>
                <line x1="9" y1="1" x2="9" y2="4"></line>
                <line x1="15" y1="1" x2="15" y2="4"></line>
                <line x1="9" y1="20" x2="9" y2="23"></line>
                <line x1="15" y1="20" x2="15" y2="23"></line>
                <line x1="20" y1="9" x2="23" y2="9"></line>
                <line x1="20" y1="14" x2="23" y2="14"></line>
                <line x1="1" y1="9" x2="4" y2="9"></line>
                <line x1="1" y1="14" x2="4" y2="14"></line>
              </svg>
            </div>
            <div class="function-label">MotoPlay</div>
          </div>
          <div class="function-item" @click="openVehicleSettings">
            <div class="function-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path
                  d="M12 2c-.8 0-1.5.5-1.8 1.2l-.1.3c-.2.6-.8 1-1.5 1-.4 0-.8-.1-1.1-.3l-.3-.2c-.7-.5-1.7-.4-2.3.2l-1 1c-.6.6-.7 1.5-.2 2.3l.2.3c.2.3.3.7.3 1.1 0 .7-.4 1.3-1 1.5l-.3.1C2.5 10.5 2 11.2 2 12c0 .8.5 1.5 1.2 1.8l.3.1c.6.2 1 .8 1 1.5 0 .4-.1.8-.3 1.1l-.2.3c-.5.7-.4 1.7.2 2.3l1 1c.6.6 1.5.7 2.3.2l.3-.2c.3-.2.7-.3 1.1-.3.7 0 1.3.4 1.5 1l.1.3c.3.7 1 1.2 1.8 1.2s1.5-.5 1.8-1.2l.1-.3c.2-.6.8-1 1.5-1 .4 0 .8.1 1.1.3l.3.2c.7.5 1.7.4 2.3-.2l1-1c.6-.6.7-1.5.2-2.3l-.2-.3c-.2-.3-.3-.7-.3-1.1 0-.7.4-1.3 1-1.5l.3-.1c.7-.3 1.2-1 1.2-1.8 0-.8-.5-1.5-1.2-1.8l-.3-.1c-.6-.2-1-.8-1-1.5 0-.4.1-.8.3-1.1l.2-.3c.5-.7.4-1.7-.2-2.3l-1-1c-.6-.6-1.5-.7-2.3-.2l-.3.2c-.3.2-.7.3-1.1.3-.7 0-1.3.4-1.5 1l-.1.3C13.5 2.5 12.8 2 12 2zm0 8c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z" />
              </svg>
            </div>
            <div class="function-label">
              车辆设置
            </div>
          </div>
          <div class="function-item" @click="findVehicle">
            <div class="function-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
                <path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path>
              </svg>
            </div>
            <div class="function-label">寻车</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 骑行数据 -->
    <div class="riding-data">
      <div class="riding-header" @click="goToMileageDetail">
        我的骑行
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <polyline points="9 18 15 12 9 6"></polyline>
        </svg>
      </div>
      <div class="riding-stats">
        <div class="stat-item">
          <div class="stat-value" v-html="formatRidingTime(currentVehicle?.ridingTimeMonthUnitMinute)"></div>
          <div class="stat-label">本月总时长</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentVehicle?.rideMileageMonth || '0' }}<span class="stat-unit">km</span></div>
          <div class="stat-label">本月行驶距离</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentVehicle?.avgVelocityMonth || '0' }}<span class="stat-unit">km/h</span></div>
          <div class="stat-label">本月行驶均速</div>
        </div>
      </div>


    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { showLoadingToast, closeToast, showSuccessToast, showFailToast, showToast } from 'vant';
import { Icon as VanIcon } from 'vant';
import { getVehicleList, getVcuLockStatus, networkUnlock } from '@/api/vehicle';
import { useVehicleStore } from '@/stores/vehicle';
import { useUserStore } from '@/stores/user';
import { getLocationByHttp } from '@/utils/geo-location.js';
import { useApiPolling } from '@/utils/api-polling.js';
import * as echarts from 'echarts/core';
import { RadarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册ECharts需要的组件
echarts.use([
  RadarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  CanvasRenderer
]);

// 签到API
import { appSigninInfoApi, appSigninApi, getUserSettingOtherApi } from '@/api/signin';

const router = useRouter();
const vehicleStore = useVehicleStore();
const userStore = useUserStore();

// 车辆列表和当前选中车辆
const vehicleList = computed(() => vehicleStore.vehicleList);
const currentIndex = computed(() => vehicleStore.currentVehicleIndex);
const currentVehicle = computed(() => vehicleStore.getCurrentVehicle());

// 当前车辆图片：优先后端合并返回的 customImage，其次使用原图字段
const currentVehicleImage = computed(() => {
  const v = currentVehicle.value || {};
  return (
    v.customImage || v.custom_image || v.vehiclePicUrl || v.vehicleScalePicUrl || v.vehicleBackPicUrl || ''
  );
});

// 车辆下拉弹出层
const showVehiclePopup = ref(false);

// 切换选择的车辆
const switchVehicle = (index) => {
  vehicleStore.setCurrentVehicleIndex(index);
  showVehiclePopup.value = false;
};

// 属性中获取指定的值
const getIotPropertyValue = (identify) => {
  if (!currentVehicle.value?.iotProperties) return null;

  const property = currentVehicle.value.iotProperties.find(
    prop => prop.identify === identify
  );

  return property?.value || null;
};

// 充电状态与电量动画
const actualSoc = computed(() => {
  const raw = currentVehicle.value?.bmssoc ?? getIotPropertyValue('BMSSOC') ?? 0;
  const n = Number(raw);
  if (!Number.isFinite(n)) return 0;
  return Math.max(0, Math.min(100, Math.round(n)));
});

const isCharging = computed(() => {
  const v = currentVehicle.value;
  const chargeFields = [
    v?.chargeState,
    getIotPropertyValue('ChargeState'),
    getIotPropertyValue('BMSChargeState')
  ];
  return chargeFields.some((x) => String(x) === '1');
});

const displayedSoc = ref(0);
let chargeAnimTimer = null;

const stopChargeAnim = () => {
  if (chargeAnimTimer) {
    clearInterval(chargeAnimTimer);
    chargeAnimTimer = null;
  }
};

const startChargeAnim = () => {
  stopChargeAnim();
  displayedSoc.value = 0;
  const stepMs = 50;
  chargeAnimTimer = setInterval(() => {
    const target = actualSoc.value || 0;
    if (displayedSoc.value >= target) {
      displayedSoc.value = 0; // 循环自增效果
    } else {
      displayedSoc.value += 1;
    }
  }, stepMs);
};

watch([isCharging, actualSoc], ([charging]) => {
  if (charging) {
    startChargeAnim();
  } else {
    stopChargeAnim();
    displayedSoc.value = actualSoc.value;
  }
}, { immediate: true });

// 顶部状态栏：计算属性（支持乐观覆盖）
const isLocked = computed(() => {
  if (overrideLocked.value !== null) return !!overrideLocked.value;
  const v = currentVehicle.value;
  const iot = getIotPropertyValue('HeadLockState');
  return v?.headLockState === '1' || iot === '1';
});

// GSM dBm（越接近0越强，常见 -50 ~ -110）
const signalDbm = computed(() => {
  const raw = currentVehicle.value?.gsmRxLev ?? getIotPropertyValue('GSMRxLev');
  if (raw === undefined || raw === null || raw === '') return null;
  const num = Number(raw);
  return Number.isFinite(num) ? num : null;
});

// 5格信号条：≥ -65(5)，≥ -75(4)，≥ -85(3)，≥ -95(2)，≥ -105(1)，否则0
const signalBars = computed(() => {
  const v = signalDbm.value;
  if (v == null) return 0;
  if (v >= -65) return 5;
  if (v >= -75) return 4;
  if (v >= -85) return 3;
  if (v >= -95) return 2;
  if (v >= -105) return 1;
  return 0;
});

const signalClass = computed(() => {
  const b = signalBars.value;
  if (b >= 4) return 'ok';
  if (b >= 2) return 'mid';
  if (b >= 1) return 'warn';
  return '';
});

// 辅助函数: 获取IoT属性描述
const getIotPropertyDescription = (identify) => {
  if (!currentVehicle.value?.iotProperties) return null;

  const property = currentVehicle.value.iotProperties.find(
    prop => prop.identify === identify
  );

  return property?.describe || null;
};

// 辅助函数: 从车辆对象中获取IoT属性值
const getVehicleIotProperty = (vehicle, identify) => {
  if (!vehicle?.iotProperties) return null;

  const property = vehicle.iotProperties.find(
    prop => prop.identify === identify
  );

  return property?.value || null;
};

const address = ref('获取中...');

// 签到卡片状态（该页默认隐藏，独立到“我的积分”页面）
const showSignCard = ref(false);
const todaySigned = ref(false);
const continuousDays = ref(0);
const totalSignDays = ref(0);
const totalPoints = ref(0);
const userDetail = ref(null);
const lastSignTime = ref('');
const statusMessage = ref('');
const statusType = ref(''); // success / error

// 加载签到信息
const loadSignData = async () => {
  try {
    const res = await appSigninInfoApi({});
    if (res && (res.code === 200 || res.success)) {
      const data = res.data || {};
      todaySigned.value = !!(data.todaySigned ?? data.todaySign);
      continuousDays.value = Number(data.continuousDays ?? data.continuityDays ?? 0);
      totalSignDays.value = Number(data.totalSignDays ?? data.totalDays ?? 0);
      totalPoints.value = Number(data.pointsBalance ?? data.integral ?? 0);
      if (data.lastSignTime || data.lastSignIn) {
        const last = new Date(data.lastSignTime || data.lastSignIn);
        lastSignTime.value = last.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
      } else {
        lastSignTime.value = '';
      }
    }
  } catch (e) {
    // 静默失败，保留默认展示
    console.error('加载签到信息失败:', e);
  }
};

// 加载用户详细信息（含积分）
const loadUserDetail = async () => {
  try {
    const uid = userStore?.userInfo?.userData?.id || userStore?.userId;
    console.log('用户ID:', uid, userStore?.userInfo?.userData);

    if (!uid) return;
    const res = await getUserSettingOtherApi(uid);
    console.log('用户详情:', res);
    if (res && (res.code === 200 || res.success || res.code === '10000')) {
      const detail = res.data || {};
      userDetail.value = detail;
      const points = Number(
        detail.pointsBalance ?? detail.integral ?? detail.points ?? detail.score ?? 0
      );
      if (!Number.isNaN(points)) totalPoints.value = points;
    }
  } catch (e) {
    console.error('加载用户详情失败:', e);
  }
};

// 点击签到
const onSignButtonClick = async () => {
  if (todaySigned.value) return;
  statusMessage.value = '正在签到...';
  statusType.value = '';
  try {
    const res = await appSigninApi({});
    if (res && (res.code === 200 || res.success)) {
      statusMessage.value = '签到成功！';
      statusType.value = 'success';
      await loadSignData();
      await loadUserDetail();
    } else {
      statusMessage.value = '签到失败';
      statusType.value = 'error';
    }
  } catch (e) {
    statusMessage.value = '签到失败，请稍后重试';
    statusType.value = 'error';
  }
};


const fetchAddress = async () => {
  if (!currentVehicle.value?.location) {
    address.value = '暂无位置信息';
    return;
  }

  try {
    const res = await getLocationByHttp({
      longitude: currentVehicle.value.location.longitude,
      latitude: currentVehicle.value.location.latitude,
      coordinateSystem: currentVehicle.value.coordinateSystem
    });

    if (res.status === 'success') {
      address.value = res.formattedAddress;
    } else {
      address.value = '解析地址失败';
    }
  } catch (error) {
    console.error('获取地址失败:', error);
    address.value = '获取地址失败';
  }
};
watch(
  () => currentVehicle.value?.location,
  (newLocation) => {
    if (newLocation) {
      fetchAddress();
    }
  },
);

// 格式化骑行时间
const formatRidingTime = (minutes) => {
  if (!minutes) return '0h 0min';

  const hours = Math.floor(Number(minutes) / 60);
  const mins = Number(minutes) % 60;

  return `${hours}<span class="stat-unit">h</span> ${mins}min`;
};


// 获取车辆数据
const isRefreshing = ref(false);
const fetchVehicleData = async () => {
  // showLoadingToast({
  //   message: '获取车辆数据...',
  //   forbidClick: true,
  //   duration: 0,
  // });

  try {
    const response = await getVehicleList();
    // loadUserDetail();

    if (response?.code === '10000') {
      const d = response?.data;
      const list = Array.isArray(d)
        ? d
        : (d?.vehicles || d?.vehicleList || d?.list || []);
      if (Array.isArray(list) && list.length > 0) {
        vehicleStore.setVehicleList(list);
      } else {
        showFailToast(response.message || '没有车辆信息');
        if (import.meta.env.DEV) { useDevMockData(); }
      }
      // 服务器返回后，以服务端为准，取消本地锁状态覆盖
      overrideLocked.value = null;
      // showSuccessToast('获取成功');
    } else {
      showFailToast(response?.message || '获取车辆列表失败');
      if (import.meta.env.DEV) { useDevMockData(); }
    }
  } catch (error) {
    console.error('获取车辆数据失败:', error);
    showFailToast(error.response?.data?.message || error.message || '获取车辆数据失败');

    // 如果请求失败，使用模拟数据（仅开发环境）
    if (import.meta.env.DEV) {
      useDevMockData();
    }
  } finally {
    closeToast();
    isRefreshing.value = false;
  }
};

// 开发环境使用模拟数据
const useDevMockData = () => {
  const mockData = [
    {
      "vinNo": "358122500023238",
      "deviceName": "863091069190002",
      "bindStartTime": "2025.03.14 20:03:41",
      "fate": "2130",
      "vehicleName": "已损老年代步工具",
      "vehiclePicUrl": "https://oss-cfmoto.zeehoev.com/uploads/zeeho-client-pc/media/1730794580446.png",
      "vehicleBackPicUrl": "https://cfmoto.oss-cn-hangzhou.aliyuncs.com/IMD/app/vehicle-buy.png",
      "rideMileageMonth": "33.6",
      "ridingTimeMonth": "3.1",
      "ridingTimeMonthUnitMinute": "192",
      "avgVelocityMonth": "10",
      "bmssoc": "72",
      "hmiRidableMile": "79",
      "gsmRxLev": "-86.0",
      "gsmRxLevValue": "中",
      "headLockState": "1",
      "rideState": "在线",
      "onlineStatus": "online",
      "location": {
        "longitude": 116.96589832801736,
        "latitude": 39.75174626244693,
        "altitude": 13.9,
        "coordinateSystem": "2",
        "locationTime": "08/08 15:17"
      },
      "vehicleScalePicUrl": "https://oss-cfmoto.zeehoev.com/uploads/zeeho-client-pc/media/1730794580446.png",
      "totalRideMile": "1241.9",
      "iotProperties": [
        {
          "name": "剩余电量",
          "identify": "BMSSOC",
          "value": "72",
          "time": "1754637443064",
          "describe": null
        },
        {
          "name": "GSM信号强度",
          "identify": "GSMRxLev",
          "value": "-86",
          "time": "1754619464060",
          "describe": "中"
        }
      ]
    }
  ];

  vehicleStore.setVehicleList(mockData);
};

const isLongPressing = ref(false);
const pressProgress = ref(0);
const longPressThreshold = 200;
let pressStartTime = 0;
let progressRaf = 0;
let longPressTimeout = 0;
let hasTriggered = false;
let longPressAction = null; // 'unlock' | 'lock' | null

//true=已关锁，false=未关锁
const overrideLocked = ref(null);

const vibrate = (pattern) => {
  try {
    if (typeof navigator !== 'undefined' && navigator?.vibrate) {
      navigator.vibrate(pattern);
    }
  } catch (_) { }
};

const resetPressState = () => {
  isLongPressing.value = false;
  pressProgress.value = 0;
  hasTriggered = false;
  if (progressRaf) {
    cancelAnimationFrame(progressRaf);
    progressRaf = 0;
  }
  if (longPressTimeout) {
    clearTimeout(longPressTimeout);
    longPressTimeout = 0;
  }
  longPressAction = null;
};

const updateProgress = () => {
  if (!isLongPressing.value) return;
  const elapsed = Date.now() - pressStartTime;
  const pct = Math.min(100, Math.round((elapsed / longPressThreshold) * 100));
  pressProgress.value = pct;
  if (pct < 100) {
    progressRaf = requestAnimationFrame(updateProgress);
  }
};

const startLongPress = () => {
  if (!currentVehicle.value?.vinNo) {
    showFailToast('未找到车辆');
    return;
  }
  resetPressState();
  isLongPressing.value = true;
  pressStartTime = Date.now();
  progressRaf = requestAnimationFrame(updateProgress);
  vibrate(10);
  // 根据当前锁态决定本次长按的目标动作
  longPressAction = isLocked.value ? 'unlock' : 'lock';
  longPressTimeout = setTimeout(() => {
    if (!hasTriggered) {
      hasTriggered = true;
      if (longPressAction === 'unlock') {
        triggerUnlock();
      } else if (longPressAction === 'lock') {
        triggerLock();
      }
    }
  }, longPressThreshold);
};

const endLongPress = () => {
  resetPressState();
};

const triggerUnlock = async () => {
  try {
    const vin = currentVehicle.value?.vinNo;
    // showLoadingToast({ message: '检查关锁状态...', duration: 0, forbidClick: true });
    const res = await getVcuLockStatus(vin);
    // code: "10000" 为成功
    if (res?.code === '10000') {
      const status = res?.data?.lockStatus;
      // 0 视为关锁，需要开锁
      if (status === 0) {
        closeToast();
        // showLoadingToast({ message: '发送开锁指令...', duration: 0, forbidClick: true });
        const unlockRes = await networkUnlock({ lockFlag: 1, vinNo: vin });
        // closeToast();
        if (unlockRes?.code === '10000') {
          // showSuccessToast('已发送开锁指令');
          overrideLocked.value = false; // 乐观更新：显示为未关锁
          showSuccessToast('已开锁');
          vibrate([30, 80, 30]);
          setTimeout(() => { fetchVehicleData(); }, 1000);
        } else {
          // showFailToast(unlockRes?.message || '开锁失败');
        }
      } else {
        closeToast();
        showToast('当前不是关锁状态');
      }
    } else {
      closeToast();
      showFailToast(res?.message || '查询关锁状态失败');
    }
  } catch (e) {
    closeToast();
    showFailToast(e?.response?.data?.message || e?.message || '操作失败');
  } finally {
    resetPressState();
  }
};

// 点击关锁
const triggerLock = async () => {
  try {
    const vin = currentVehicle.value?.vinNo;
    if (!vin) {
      showFailToast('未找到车辆');
      return;
    }
    // showLoadingToast({ message: '发送关锁...', duration: 0, forbidClick: true });
    const resp = await networkUnlock({ lockFlag: 0, vinNo: vin });
    if (resp?.code === '10000') {
      overrideLocked.value = true; // 乐观更新：显示为已关锁
      showSuccessToast('已关锁');
      vibrate([60]);
      setTimeout(() => { fetchVehicleData(); }, 1000);
    } else {
      showFailToast(resp?.message || '关锁失败');
    }
  } catch (e) {
    showFailToast(e?.response?.data?.message || e?.message || '关锁失败');
  }
};

// 顶部刷新点击
const onRefreshClick = async () => {
  if (isRefreshing.value) return;
  isRefreshing.value = true;
  await fetchVehicleData();
  showToast('已刷新');
};

const openMotoPlay = () => {
  if (!currentVehicle.value?.motoPlay) {
    showToast('当前车辆不支持 MotoPlay');
    return;
  }
  // showToast('打开 MotoPlay');
  showToast('敬请期待...');
};

const openVehicleSettings = () => {
  const vin = currentVehicle.value?.vinNo;
  // if (!vin) {
  //   showFailToast('未找到车辆');
  //   return;
  // }
  router.push({ path: '/vehicle-settings', query: { vinNo: vin } });
};

const findVehicle = () => {
  showToast('敬请期待...');
};

// 进入车辆详情
const goToVehicleDetail = () => {
  const v = currentVehicle.value;
  if (!v) {
    showFailToast('未找到当前车辆');
    return;
  }
  const vehicleId = v.vehicleId || v.vinNo || v.deviceName;
  const vinNo = v.vinNo || '';
  if (!vehicleId) {
    showFailToast('车辆缺少ID，无法查看');
    return;
  }
  router.push({
    path: '/vehicle-detail',
    query: { vehicleId, vinNo }
  });
};

// 跳转到“我的积分”页面
const goToUserPoints = () => {
  router.push({ path: '/user-points' });
};

// 跳转到位置信息
const goToLocation = () => {
  // if (currentVehicle.value?.location?.longitude) {
  //   // 跳转到地图页面或导航
  //   showToast('跳转到地图');
  // }
};

// 跳转到公里数详情
const goToMileageDetail = () => {
  router.push({
    path: '/mileage-detail',
    query: { vinNo: currentVehicle.value?.vinNo }
  });
};

// 跳转到电池详情

const goToBatteryDetail = () => {
  router.push({
    path: '/battery-detail',
    query: { vinNo: currentVehicle.value?.vinNo }
  });
};


// 格式化绑定日期
const formatBindDate = (dateStr) => {
  if (!dateStr) return '';

  if (dateStr.includes('.')) {
    return dateStr.split(' ')[0].replace(/\./g, '-');
  }

  return dateStr;
};

const {
  start,
  stop,
  executeNow,
  updateInterval,
  setup
} = useApiPolling(fetchVehicleData, 60000, false);

// 组件销毁时停止轮询
onUnmounted(() => {
  stop();
  stopChargeAnim();
  // 清理长按相关状态与动画
  if (typeof resetPressState === 'function') {
    resetPressState();
  }
});




onMounted(() => {

  start();
});

</script>

<style lang="scss" scoped>
.vehicle-info-page {
  background-color: #f8f8fac9;
  height: 100%;

  &::-webkit-scrollbar {
    display: none;
  }


  // 顶部信息栏（含用户与连接状态）
  .top-info-bar {
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 10px 12px 8px;

    border-radius: 0 0 12px 12px;

    .top-row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .dropdown-container {
        .dropdown-title {
          display: flex;
          align-items: center;

          .title-text {
            font-size: 20px;
            font-weight: 700;
            margin-right: 4px;
          }
        }
      }

      .top-right {
        display: flex;
        align-items: center;

        .refresh-button {
          margin-left: 10px;
          width: 26px;
          height: 26px;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.2);
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          &:hover {
            background-color: rgba(255, 255, 255, 0.3);
          }

          &.spinning {
            animation: spin 0.9s linear infinite;
          }
        }

        // 未关锁（开锁）状态：蓝色边框与蓝色前景
        &.lock.warn {
          border: 1px solid #3b82f6;
          color: #3b82f6;
          background-color: rgba(59, 130, 246, 0.08);
          border-radius: 10px;
        }
      }
    }


    /* .connection-row removed (unused) */

    .status-chips {
      display: flex;
      flex-wrap: nowrap;
      padding-bottom: 2px;

      &::-webkit-scrollbar {
        display: none;
      }

      .chip {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 6px;
        font-size: 11px;
        box-shadow: none;
        backdrop-filter: blur(6px);

        .chip-icon {
          display: inline-flex;
        }

        .chip-text {
          white-space: nowrap;
        }

        &.signal .bars {
          display: inline-flex;
          align-items: flex-end;
          gap: 2px;
          height: 10px;
          // margin-right: 2px;

          .bar {
            width: 2px;
            background: rgba(43, 241, 3, 0.61);
            border-radius: 2px;
          }

          .bar:nth-child(1) {
            height: 3px;
          }

          .bar:nth-child(2) {
            height: 5px;
          }

          .bar:nth-child(3) {
            height: 7px;
          }

          .bar:nth-child(4) {
            height: 9px;
          }

          .bar.active {
            background: #1eff00;
          }
        }


        &.online .dot {
          width: 6px;
          height: 6px;
          border-radius: 50%;

          &.on {
            background: #22c55e;
          }

          &.off {
            background: #ef4444;
          }
        }
      }
    }

  }


  // 车辆图片
  .vehicle-image-container {
    width: 100%;
    max-height: 250px;

    .vehicle-image-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      padding-bottom: 50%;
      overflow: hidden;
      border-radius: 12px;

      .vehicle-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
  }

  // 位置信息
  .location-info {
    max-width: 95%;
    margin: 5px auto 10px auto;
    background-color: white;
    border-radius: 20px;
    padding: 8px 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .location-icon {
      width: 20px;
      height: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 5px;

      svg {
        color: #4285F4;
      }
    }

    .location-text {
      font-size: 12px;
      color: #333;
    }
  }

  // 车辆数据
  .vehicle-data-container {
    display: flex;
    margin: 0 16px 16px;

    gap: 12px;

    .data-box {
      background-color: white;
      border-radius: 12px;
      padding: 10px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      &.left-data {
        flex: 1;
        padding: 10px 15px;
        box-sizing: border-box;

        .data-content {
          .data-section {
            margin-bottom: 16px;

            &:last-child {
              margin-bottom: 0;
            }



            .data-title {
              font-size: 12px;
              color: #666;
              // margin-bottom: 6px;
            }

            .data-value-large {
              font-size: 24px;
              font-weight: 600;
              color: #333;

              .data-unit {
                font-size: 14px;
                font-weight: normal;
                margin-left: 2px;
              }
            }

            /* removed empty .battery-bar block; unified battery styles are defined globally below */

            /* .battery-detail-link removed (unused) */
          }
        }
      }

      &.right-data {
        width: 58%;

        .function-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          grid-gap: 5px;

          .function-item {
            width: 100%;
            height: 75px;
            background-color: #f9fafb;
            border-radius: 10px;
            padding: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.2s;
            position: relative; // 为长按环形进度定位
            overflow: visible;

            // 禁用文本选择与系统长按菜单
            &.no-select {
              -webkit-user-select: none;
              user-select: none;
              -webkit-touch-callout: none;
              touch-action: manipulation;
            }

            // 开锁状态卡片：蓝色边框与浅蓝背景
            &.unlock-state {
              border: 1px solid #3b82f6;
              background-color: rgba(59, 130, 246, 0.06);
            }

            // 关锁状态卡片：红色边框与浅红背景
            /* .lock-state removed (unused) */

            &:hover {
              background-color: #f3f4f6;
            }

            .function-icon {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              background-color: rgba(37, 99, 235, 0.1);
              display: flex;
              justify-content: center;
              align-items: center;
              margin-bottom: 8px;

              svg {
                color: #2563eb;
              }

              &.lock-icon {
                background-color: rgba(239, 68, 68, 0.1);

                svg {
                  color: #ef4444;
                }
              }

              &.unlock-icon {
                background-color: rgba(59, 130, 246, 0.12);

                svg {
                  color: #3b82f6;
                }
              }
            }

            .function-label {
              font-size: 12px;
              color: #333;
              line-height: 1.3;

              .pressing-text {
                color: #ef4444;
              }

              .progress-bar {
                margin-top: 4px;
                height: 4px;
                background-color: #e5e7eb;
                border-radius: 2px;
                overflow: hidden;
                width: 100%;

                .progress {
                  height: 100%;
                  background-color: #ef4444;
                  border-radius: 2px;
                }
              }
            }
          }
        }
      }
    }
  }

  // 骑行数据
  .riding-data {
    margin: 0 16px 16px;
    background-color: white;
    border-radius: 12px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .riding-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 16px;
      color: #333;
    }

    .riding-stats {
      display: flex;
      justify-content: space-between;

      .stat-item {
        text-align: center;
        flex: 1;

        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;

          .stat-unit {
            font-size: 12px;
            font-weight: normal;
            color: #666;
          }
        }

        .stat-label {
          font-size: 12px;
          color: #666;
        }
      }
    }

    // 雷达图骑行数据可视化
    /* .radar-chart-container removed (unused) */
  }

  // 车辆数据详情
  /* .vehicle-details-section removed (unused) */

}

// 车辆切换弹出层
.vehicle-popup {
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  overflow: hidden;
  box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.vehicle-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  position: relative;
  z-index: 2;

  .popup-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .close-icon {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background-color: #f5f5f5;
    transition: background-color 0.2s;

    &:active {
      background-color: #e0e0e0;
    }

    svg {
      color: #666;
    }
  }
}

.popup-scroll-container {
  height: calc(50vh - 56px - env(safe-area-inset-bottom, 0));
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  background: #fff;
}

.vehicle-list {
  padding: 8px 16px;

  .vehicle-item {
    position: relative;
    border-radius: 12px;
    display: flex;
    padding: 6px;
    margin-bottom: 10px;
    background-color: #f9f9f9;
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    &:last-child {
      margin-bottom: 0;
    }

    &.active {
      background-color: #f0f7ff;
      box-shadow: 0 2px 8px rgba(37, 99, 235, 0.1);
      transform: translateY(-2px);
    }

    .vehicle-item-image {
      width: 100px;
      height: 70px;
      overflow: hidden;
      border-radius: 8px;
      margin-right: 14px;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 90%;
        height: 90%;
        object-fit: contain;
      }
    }

    .vehicle-item-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .vehicle-item-name {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 6px;
      }

      .vehicle-item-type {
        font-size: 13px;
        color: #666;
      }

      .vehicle-item-mileage {
        font-size: 13px;
        color: #666;
        margin-top: 6px;
      }
    }

    .vehicle-item-status {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-end;

      .battery-info {
        display: flex;
        align-items: center;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;

        svg {
          margin-right: 4px;
        }
      }

      .online-status {
        font-size: 12px;
        padding: 2px 10px;
        border-radius: 12px;

        &.online {
          background-color: rgba(16, 185, 129, 0.1);
          color: #10b981;
        }

        &.offline {
          background-color: rgba(239, 68, 68, 0.1);
          color: #ef4444;
        }
      }
    }

    .vehicle-select-indicator {
      position: absolute;
      top: -5px;
      right: 1px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #2563eb;
      display: flex;
      align-items: center;
      justify-content: center;

      svg {
        color: #fff;
        width: 16px;
        height: 16px;
      }
    }
  }
}

// 电量进度条样式（放置在样式段，避免污染模板）
.vehicle-info-page {
  .vehicle-data-container {
    .battery-bar {
      position: relative;
      width: 100%;
      height: 10px;
      background: #eef2f7;
      border-radius: 6px;
      overflow: hidden;
      margin-top: 6px;
    }

    .battery-level {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 0%;
      background: linear-gradient(90deg, #16a34a, #22c55e);
      transition: width 0.35s ease-in-out;
    }

    .battery-level.charging {
      background-image:
        linear-gradient(90deg, #16a34a, #22c55e),
        repeating-linear-gradient(45deg, rgba(255, 255, 255, 0.35) 0, rgba(255, 255, 255, 0.35) 8px, rgba(255, 255, 255, 0.15) 8px, rgba(255, 255, 255, 0.15) 16px);
      background-size: 100% 100%, 24px 24px;
      background-blend-mode: overlay;
      animation: chargingStripes 1s linear infinite;
    }
  }
}

@keyframes chargingStripes {
  0% {
    background-position: 0 0, 0 0;
  }

  100% {
    background-position: 0 0, 24px 0;
  }
}
</style>